var express = require('express');
var router = express.Router();

var multiparty = require('multiparty');
var url = require('url');
var fs = require('fs');

router.get('/', function(req,res, next){
    res.sendFile(__dirname.substring(0, __dirname.lastIndexOf('\\')) + '/views/index.html');
});

router.post('/', function(req, res, next){
    var form = new multiparty.Form();
    form.encoding = 'utf-8';
    form.uploadDir = './public/files';
    form.maxFileSize = 20*1024*1024;
    form.maxFields = 1000;
    form.parse(req, function(err, fields, files){

        console.log(fields);
        console.log(files);

        if(err) console.log(err);
        else{
            var inputFile = files.inputFile[0];
            var uploadedPath = inputFile.path;
            var destPath = './public/files/' + inputFile.originalFilename;
            fs.rename(uploadedPath, destPath, function(err){
                if(err) throw err;
            })
        }
        res.end();
    });
});

module.exports = router;